module Concerns::ProjectV2
  extend ActiveSupport::Concern
  included do
  end

  def show_v2
    @panel_heading = "#{@project.name} | 老版测试页面"
    @v2 = true
    @rds = rds
  end

  def shut_queues_v2
    @panel_heading = "#{@project.name} | 查询排队放弃"
    return if request.get?
    rds[:im_queues_start_time] = params[:im_queues_start_time] if params[:im_queues_start_time].present?
    rds[:im_queues_end_time] = params[:im_queues_end_time] if params[:im_queues_end_time].present?
    rds[:im_queues_page] = params[:im_queues_page] if params[:im_queues_page].present?
    rds[:im_queues_per_page] = params[:im_queues_per_page] if params[:im_queues_per_page].present?
    url = "#{base_url_v2}/im/im_queues"
    req_params = get_params_with_sign_v2
    req_params[:start_time] = rds[:im_queues_start_time]
    req_params[:end_time] = rds[:im_queues_end_time]
    req_params[:page] = rds[:im_queues_page]
    req_params[:per_page] = rds[:im_queues_per_page]

    Rails.logger.info "req_params #{req_params.inspect}"
    rds[:shut_queues_req] = "#{url}?#{req_params.to_query}"
    res = RestClient.get "#{url}?#{req_params.to_query}", JSON_HEADERS
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      rds[:shut_queues_res] = res
    end

    redirect_back(fallback_location: show_v2_project_path(@project))
  rescue => e
    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def queue_status_v2
    @panel_heading = "#{@project.name} | 用户队列状态"
    return if request.get?
    url = "#{base_url_v2}/im/queue_status"
    req_params = get_params_with_sign_v2
    req_params[:customer_token] = rds[:open_api_token]
    req_params[:web_token] = rds[:web_token]
    req_params[:sdk_token] = rds[:sdk_token]
    req_params[:session_key] = rds[:session_key]

    Rails.logger.info "req_params #{req_params.inspect}"

    res = RestClient.get "#{url}?#{req_params.to_query}", JSON_HEADERS
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      rds[:queue_res] = res
    end

    redirect_back(fallback_location: show_v2_project_path(@project))
  rescue => e
    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def customer_status_v2
    @panel_heading = "#{@project.name} | 客户状态"
    return if request.get?
    url = "#{base_url_v2}/im/customer_status"
    req_params = get_params_with_sign_v2
    req_params[:customer_token] = rds[:open_api_token]

    Rails.logger.info "req_params #{req_params.inspect}"

    res = RestClient.get "#{url}?#{req_params.to_query}", JSON_HEADERS
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      rds[:customer_status_res] = res
    end

    redirect_back(fallback_location: show_v2_project_path(@project))
  rescue => e
    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def set_settings_v2
    @panel_heading = "#{@project.name} | api token 获取"

    return if request.get?

    rds.set(:server_domain, params["server_domain"])
    rds.set(:email      , params["email"])  
    rds.set(:password     , params["password"])

    redirect_back(fallback_location: show_v2_project_path(@project))

  end

  def base_url_v2
    url = "http://#{rds[:server_domain]}/open_api_v1"
  end
  
  def get_open_api_auth_token_v2
    url = "#{base_url_v2}/log_in"
    body = {
      email: rds[:email],
      password: rds[:password],
    }.to_json
    headers = {content_type: :json, accept: :json}

    res = RestClient.post url, body, headers
    Rails.logger.info res.inspect
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      rds[:open_api_auth_token] = res['open_api_auth_token']
    end
    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def auth_token_v2
    rds[:open_api_auth_token]
  end

  def get_sign_v2(timestamp)
    sign = Digest::SHA1.hexdigest("#{rds[:email]}&#{auth_token_v2}&#{timestamp}")
  end
  def get_params_with_sign_v2
    timestamp = Time.now.to_i
    {
      email: rds[:email],
      timestamp: timestamp,
      sign: get_sign_v2(timestamp),
    }
  end

  def survey_vote_v2
    @panel_heading = "#{@project.name} | 满意度调查"
    return if request.get?
    url = "#{base_url_v2}/im/sessions/survey"
    req_params = get_params_with_sign_v2
    req_params[:customer_token] = rds[:open_api_token]
    req_params[:assign_type] = params[:assign_type]

    req_params[:im_sub_session_id] = params[:im_sub_session_id]
    req_params[:option_id] = params[:option_id]
    req_params[:remark] = params[:remark]

    Rails.logger.info "req_params #{req_params.inspect}"

    res = RestClient.post url, req_params, JSON_HEADERS
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      rds[:option_id] = params[:option_id]
      rds[:remark] = params[:remark]
      rds[:survey_res] = res
    end

    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def get_session_v2
    @panel_heading = "#{@project.name} | 创建会话"
    return if request.get?
    url = "#{base_url_v2}/im/sessions"
    req_params = get_params_with_sign_v2
    req_params[:customer_token] = params[:open_api_token].presence || rds[:open_api_token]
    req_params[:assign_type] = params[:assign_type]
    req_params[:agent_id] = params[:agent_id]
    req_params[:group_id] = params[:group_id]
    req_params[:channel] = params[:channel]
    req_params[:robot_role_id] = params[:robot_role_id]

    rds[:assign_type] = params[:assign_type]
    rds[:agent_id] = params[:agent_id]
    rds[:group_id] = params[:group_id]
    rds[:channel] = params[:channel]
    rds[:robot_role_id] = params[:robot_role_id]

    Rails.logger.info "req_params #{req_params.inspect}"

    res = RestClient.post url, req_params, JSON_HEADERS
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      if res['code'] == 1000 && res['assign_info'].present?

        info = res['assign_info']
        rds[:assign_type] = res['assign_type']
        rds[:im_sub_session_id] = info['im_sub_session_id']
        rds[:survey_options] = info['survey_options'].try(:[], 'options')
      end
      rds[:session_info] = res

    end

    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def custome_info_to_params
    JSON.parse params[:customer_info] rescue {}
  end

  JSON_HEADERS = {content_type: :json, accept: :json}
  def get_customer_v2
    @panel_heading = "#{@project.name} | 创建客户"
    @v2 = true
    return unless request.post?
    open_api_token = params[:open_api_token]
    rds[:open_api_token] = open_api_token
    custome_email = params[:custome_email]
    custome_nick_name = params[:custome_nick_name]
    customer_info = params[:customer_info]
    customer_other_emails = JSON.parse params[:customer_other_emails] rescue []
    customer_tags = params[:customer_tags]

    url = "#{base_url_v2}/customers"
    req_params = get_params_with_sign_v2
    req_params[:customer] = custome_info_to_params
    req_params[:customer]['email'] = custome_email
    req_params[:customer]['nick_name'] = custome_nick_name
    req_params[:customer]['open_api_token'] = open_api_token

    # req_params[:other_email] = customer_other_emails
    # req_params[:tags] = customer_tags
    Rails.logger.info "req_params #{req_params.inspect}"

    res = RestClient.post url, req_params, JSON_HEADERS
    rds[:customer_error] = nil
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      if res['code'] == 1000
        rds[:customer] = res['customer']
        
        rds[:customer_id] = res['customer']['id']
      else
        Rails.logger.info "customer_error"
        rds[:customer_error] = "ERROR #{Time.now.to_s}: #{res}\n"
      end
    end

    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def get_customer_by_token_v2
    @panel_heading = "#{@project.name} | 查询客户"
    @v2 = true
    return unless request.post?
    open_api_token = params[:open_api_token]
    rds[:open_api_token] = open_api_token
    custome_email = params[:customer_email]
    rds[:customer_email] = params[:customer_email] if params[:customer_email].present?
    rds[:customer_id] = params[:customer_id] if params[:customer_id].present?
    rds[:customer_cellphone] = params[:customer_cellphone] if params[:customer_cellphone].present?
    rds[:customer_weixin_open_id] = params[:customer_weixin_open_id] if params[:customer_weixin_open_id].present?
    rds[:customer_weibo_id] = params[:customer_weibo_id] if params[:customer_weibo_id].present?
    rds[:customer_search_type] = params[:customer_search_type] if params[:customer_search_type].present?


    url = "#{base_url_v2}/customers/get_customer"
    req_params = get_params_with_sign_v2
    req_params[:type] = rds[:customer_search_type]
    s_type = req_params[:type]
    req_params[:content] = case s_type
    when "token"
      rds[:open_api_token]
    else
      rds["customer_#{s_type}".to_sym]
    end


    # req_params[:other_email] = customer_other_emails
    # req_params[:tags] = customer_tags
    Rails.logger.info "req_params #{req_params.inspect}"

    res = RestClient.get "#{url}?#{req_params.to_query}", JSON_HEADERS
    rds[:customer_error] = nil
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      if res['code'] == 1000
        rds[:customer] = res['customer']
        
        rds[:customer_id] = res['customer']['id']
      else
        Rails.logger.info "customer_error"
        rds[:customer_error] = "ERROR #{Time.now.to_s}: #{res}\n"
      end
    end

    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def send_message_v2
    @panel_heading = "#{@project.name} | 发送消息"
    return if request.get?
    url = "#{base_url_v2}/im/messages"
    req_params = get_params_with_sign_v2

    req_params[:customer_token] = rds[:open_api_token]
    req_params[:assign_type] = rds[:assign_type]
    req_params[:im_sub_session_id] = rds[:im_sub_session_id]
    req_params[:type] = params[:type]
    req_params[:message_id] = [Time.now.strftime("%Y%m%d%H%M%S%L"), SecureRandom.hex(4)].join("-")
    req_params[:data] = { content: params[:content] }

    res = RestClient.post url, req_params, JSON_HEADERS
    if res.code == 200
      res = JSON.parse res
      Rails.logger.info "res: " + res.inspect
      rds[:send_message_v2_resp] = res
    end
    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def cls_push_v2
    @panel_heading = "#{@project.name} | 接收消息"
    return if request.get?
    @v2 = true
    rds.set(:push_info, '')
    redirect_back(fallback_location: show_v2_project_path(@project))
  end

  def recv_v2
    @project = Project.find(params[:id])
    @request_payload = JSON.parse request.body.read
    Rails.logger.info "request: #{@request_payload.inspect}"

    old = rds.get :push_info

    rds.set(:push_info, "#{Time.now}|#{@request_payload.inspect}\n#{old}")
    render json: ""
  end

end
